package com.qitmiaojie.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qitmiaojie.controller.chat.ChatResp;
import com.qitmiaojie.controller.chat.RequestMessage;
import com.qitmiaojie.controller.utils.Result;
import com.qitmiaojie.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @author miaojie
 * @version 1.0
 * @description TODO
 * @date 2023/3/8 18:57
 */
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    @Override
    public Result chat(String input) {
        return null;
       /* ChatResp chatResp = null;
        try {
            URL url = new URL("https://chat.51buygpt.com/message.php");
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlCon.setDoOutput(true);
            OutputStream os = urlCon.getOutputStream();
            os.write(("message=" + input).getBytes("utf-8")); // 将消息体写入请求输出流
           // os.write(("context=" + input).getBytes("utf-8")); // 将消息体写入请求输出流
            os.flush();
            os.close();

            chatResp = null;
            StringBuffer buffer = new StringBuffer();
            if (200 == urlCon.getResponseCode()) {
                log.info(urlCon.getResponseMessage());
                InputStream is = urlCon.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String str = null;
                while ((str = br.readLine()) != null) {

                    buffer.append(str);
                }
                log.info(buffer.toString());

                System.err.println(buffer);
                //chatResp = new ObjectMapper().readValue(buffer.toString(), ChatResp.class);
                log.info(chatResp.toString());
    //            System.out.println(chatResp);
            }else {
                return Result.error("error");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {

        }
        return Result.success(chatResp);*/

    }
    @Override
    public Result chatgpt(RequestMessage requestMessage) {

      /*  // 创建 OkHttpClient 对象，使用连接池
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(5, 10, TimeUnit.MINUTES))
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

// 创建 Request 对象
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("message", requestMessage.getMessage())
                .addFormDataPart("context", requestMessage.getContent())
                .build();
        Request request = new Request.Builder()
                .url("https://chat.51buygpt.com/message.php")
                .post(requestBody)
                .build();

// 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ChatResp chatResp = new ObjectMapper().readValue(response.body().byteStream(), ChatResp.class);
                log.info(chatResp.toString());
                return Result.success(chatResp);
            } else {
                return Result.error("error");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return null;
    }

   /* @Override
    public Result chatgpt(RequestMessage requestMessage) {
        ChatResp chatResp = null;
        try {

            URL url = new URL("https://chat.51buygpt.com/message.php");
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            log.info(requestMessage.toString());
            // 设置请求方法为 POST
            urlCon.setRequestMethod("POST");

// 设置请求头的 Content-Type 为 multipart/form-data
            urlCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

// 开始构造请求体
            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            String CRLF = "\r\n";
            String charset = "UTF-8";
            StringBuilder sb = new StringBuilder();
// 添加 message 参数
            sb.append("--" + boundary + CRLF);
            sb.append("Content-Disposition: form-data; name=\"message\"" + CRLF + CRLF);
            sb.append(requestMessage.getMessage() + CRLF);
// 添加 context 参数
            sb.append("--" + boundary + CRLF);
            sb.append("Content-Disposition: form-data; name=\"context\"" + CRLF + CRLF);
            sb.append(requestMessage.getContent() + CRLF);
// 添加请求体的结束标记
            sb.append("--" + boundary + "--" + CRLF);

// 将构造好的请求体写入请求输出流
            urlCon.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(urlCon.getOutputStream(), charset);
            writer.write(sb.toString());
            writer.flush();
            writer.close();


            chatResp = null;
            StringBuffer buffer = new StringBuffer();
            if (200 == urlCon.getResponseCode()) {
                log.info(urlCon.getResponseMessage());
                InputStream is = urlCon.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String str = null;
                while ((str = br.readLine()) != null) {
                    buffer.append(str);
                }
                log.info(buffer.toString());
                chatResp = new ObjectMapper().readValue(buffer.toString(), ChatResp.class);
                log.info(chatResp.toString());
                //            System.out.println(chatResp);
            }else {
                return Result.error("error");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {

        }
        return Result.success(chatResp);
    }*/
}
